<?php
$config = [
    'hostname'   => "127.0.0.1", //服务器地址
    'port'       => "3306",  // 端口
    'database'   => "test", //数据库名
    'username'   => "root", // 用户名
    'password'   => "root123456", // 密码
    'charset'    => "utf8"   // 数据库编码默认采用utf8
];
//返回数据
function  jsonArray($code=200, $msg="success", $data=[])
{
    if( empty( $data ) )
    {
        $dataArray = [ 'code'=>$code, 'msg'=>$msg ];
    }else
    {
        $dataArray = [ 'code'=>$code, 'msg'=>$msg, 'data'=>$data ];
    }
    echo json_encode( $dataArray );die;
}
//查询一条数据
function selectFind($object,$sql)
{
    $stm  = $object->prepare($sql);
    $stm->execute();
    $data = $stm->fetch(PDO::FETCH_ASSOC);
    jsonArray(200,"success",$data);
}
//查询多条数据
function select($object,$sql)
{
    $stm  = $object->prepare($sql);
    $stm->execute();
    $data = $stm->fetchAll(PDO::FETCH_ASSOC);
    jsonArray(200,"success",$data);
}
//打印命令
function dump($data)
{
    var_dump($data);die;
}

$dsn = "mysql:host=".$config['hostname'].";port=".$config['port'].";dbname=".$config['database'].";charset=".$config['charset'];
try{
    $object = new PDO(
        $dsn,
        $config['username'],
        $config['password']
    );
}catch( PDOException $e ){
    jsonArray( -101, '数据库连接失败 ' . $e->getMessage() );
}

//查询数据
$sql  = "SELECT * FROM test";
select($object,$sql);






































